package com.itheima.chinamobileai.config;


import com.itheima.chinamobileai.constants.SystemConstants;
import com.itheima.chinamobileai.tool.MyTool;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.client.advisor.vectorstore.QuestionAnswerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.ChatMemoryRepository;
import org.springframework.ai.chat.memory.repository.jdbc.JdbcChatMemoryRepository;
import org.springframework.ai.chat.memory.repository.jdbc.MysqlChatMemoryRepositoryDialect;
import org.springframework.ai.ollama.OllamaChatModel;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.ai.openai.OpenAiEmbeddingModel;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.filter.CharacterEncodingFilter;

@Configuration
public class CommonConfiguration {
    /**
     * 采用阿里的百炼大模型--中国移动客服使用的
     * @param chatModel
     * @param chatMemory
     * @return
     */
    @Bean
    public ChatClient aliModel(OpenAiChatModel chatModel,
                               ChatMemory chatMemory,
                               MyTool myTool,
                               VectorStore vectorStore) {
        return ChatClient
                .builder(chatModel) // 创建ChatClient工厂
                .defaultSystem(SystemConstants.CUSTOMER_SERVICE_SYSTEM)//设置system角色(中国移动智能客服)
                .defaultAdvisors(new SimpleLoggerAdvisor())//日志功能
                .defaultAdvisors(MessageChatMemoryAdvisor.builder(chatMemory).build())//会话保存
                .defaultAdvisors(QuestionAnswerAdvisor.builder(vectorStore)
                        .searchRequest(SearchRequest.builder() // 向量检索的请求参数
                                .similarityThreshold(0.5d) // 相似度阈值
                                .topK(2) // 返回的文档片段数量
                                .build())
                        .build())
                .defaultTools(myTool)
                .build(); // 构建ChatClient实例
    }
    /**
     * 配置向量库
     * @param embeddingModel
     * @return
     */
    @Bean
    public VectorStore vectorStore(OpenAiEmbeddingModel embeddingModel) {
        return SimpleVectorStore.builder(embeddingModel).build();
    }
}